<?php
namespace App\Services;

use AlibabaCloud\Client\AlibabaCloud;
use Illuminate\Support\Facades\Redis;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use App\Models\SmsLogModel;
use Illuminate\Support\Facades\Log;

class SmsService {
    /**
	* 生成短信验证码
	*
	* @access public
	* @return json 返回类型
	*
	*/
 	static public function code($length = 6) {
		return mt_rand(pow(10,($length-1)), pow(10,$length)-1);
	}

	/**
	* 发送短信验证码
	*
	* @access public
	* @return json 返回类型
	*
	*/
 	static public function sendCode($mobile) {
 		AlibabaCloud::accessKeyClient(config('app.sms_key'), config('app.sms_secret'))
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        $code = SELF::code();

        try {
        	//调用阿里云短信平台接口发送短信
            $info = AlibabaCloud::rpc()
                                  ->product('Dysmsapi')
                                  // ->scheme('https') // https | http
                                  ->version('2017-05-25')
                                  ->action('SendSms')
                                  ->method('POST')
                                  ->host('dysmsapi.aliyuncs.com')
                                  ->options([
                                                'query' => [
                                                  'PhoneNumbers' => $mobile,
                                                  'SignName' => config('app.sign_name'),
                                                  'TemplateCode' => config('app.template_id'),
                                                  'TemplateParam' => json_encode(['code' => $code]),
                                                ],
                                            ])
                                  ->request();

            $result = $info->toArray();

            if($result['Code'] == 'OK') {
            	//为验证码设置存活时间-----存活时间为五分钟
		      	Redis::setex($mobile.'_mobile_login', 300, $code);

              	SmsLogModel::insertGetId([
                                  'mobile' => $mobile,
                                  'code' => $code,
                                  'scene' => 0,
                                  'create_at' => time()
                              ]);

            	return ['code' => 0,'msg' => '验证码已成功发送，请注意查收', 'data' => ''];
            }
            else {
            	return ['code' => 101,'msg' => '验证码未能成功发送，请稍后重试', 'data' => ''];
            }
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
		}
	}

    /**
     * @库存不足时发送短信提醒
     * @created 在 2021/12/2 16:17 创建
     * @param Request $request
     * @author: Sun Wu
     */
    static public function sendStorageAlertMsg($msg, $mobile, $templateId)
    {
        AlibabaCloud::accessKeyClient(config('app.sms_key'), config('app.sms_secret'))
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        $code = SELF::code();

        try {
            //调用阿里云短信平台接口发送短信
            $info = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $mobile,
                        'SignName' => config('app.sign_name'),
                        'TemplateCode' => $templateId,
                        'TemplateParam' => json_encode($msg),
                    ],
                ])
                ->request();

            $result = $info->toArray();

            if($result['Code'] == 'OK') {
                return true;
            }
            else {
                return false;
            }
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }
}
